package com.jsmtr.rms.controller;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.*;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.EnumTools;
import com.jsmtr.rms.utils.StringTools;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Controller
@RequestMapping("/Do/ZZSigning")
public class DoZZSigningController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IRecommendService recommendService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    private IDoZZService doZZService;
    @Resource
    private IDoGXService doGXService;


    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);

            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);

            //结果状态
            List states=new ArrayList();
            List stateList=utilService.groupZZStateByFid(fid,"签约");
            if (stateList!=null&&stateList.size()>0){
                states.addAll(stateList);
            }else{
                states.add("未签约");
            }
            model.addAttribute("states",states);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Signing/index";
    }



    //region 20190225 变更查询为复杂查询
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("rcount").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            Map<String, Object> map = recommendService.getUserMap(page, perpage, user,_map);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {

                List<HashMap> object = (List<HashMap>)map.get("list");
                int num = 1;
                for (HashMap<String,Object> _user :  object) {

                    result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user.get("ID") + "' id='cb_" + _user.get("ID") + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='" + request.getContextPath() + "/UserResume/ViewDResume?id=" + _user.get("DRID") + "'>" + _user.get("NAME") + "</a></td>");
                    result.append("<td>" + _user.get("GENDER") + "</td>");
                    result.append("<td>" + _user.get("CODE") + "</td>");
                    result.append("<td>" + _user.get("MAJOR") + "</td>");
                    result.append("<td>" + _user.get("GRADUATIONTIME") + "</td>");
                    result.append("<td>" + _user.get("BX") + "</td>");
                    result.append("<td>" + _user.get("GUAKE") + "</td>");
                    result.append("<td>" + _user.get("HEIGHT") + "</td>");
                    result.append("<td>" + _user.get("JOB")+ "</td>");
                    result.append("<td>" + _user.get("QYSTATE")  + "</td>");
                    result.append("<td>" + (_user.get("QYREMARK") == null ? "" : _user.get("QYREMARK")) + "</td>");
                    result.append("<td>");
                    if ( _user.get("FQSTATE").toString().equals("已放弃")
                            && _user.get("FQFID").equals(flowid)) {
                        result.append("<span class='layui-badge layui-bg-gray' title='已放弃'>弃</span>");
                    } else {
                        if (!StringTools.trimNotEmpty(_user.get("QYSTATE"))||_user.get("QYSTATE").equals("未处理")) {
                            result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                        } else if (_user.get("QYSTATE").equals("未通过")||_user.get("QYSTATE").equals("不通过")||_user.get("QYSTATE").equals("不合格")||_user.get("QYSTATE").equals("未合格")) {
                            result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");

                        }else if(_user.get("QYSTATE").equals("违约")){
                            result.append("<span class='layui-badge layui-bg-green' title='违约'>违</span>");
                        }else if(_user.get("QYSTATE").equals("放弃签约")){
                            result.append("<span class='layui-badge layui-bg-green' title='放弃签约'>放</span>");
                        } else {
                            boolean bl = _user.get("FID").equals(flowid);
                            if (bl){
                                result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                            }else{
                                result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                            }
                            if (StringTools.trimNotEmpty(_user.get("NRID"))){
                                result.append("<span class='layui-badge layui-bg-blue' title='转岗(原岗位:"+_user.get("NJNAME")+")'>岗</span>");
                            }
                        }
                    }
                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        result.append("<span class='layui-badge layui-bg-blue' title='转岗(原岗位:"+_user.get("NJNAME")+")'>岗</span>");
                    }
                    result.append("</td>");
                    result.append("</tr>");

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='12'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    //endregion



    //[start] 查看某一个人投过哪些招聘方案

    @RequestMapping("/hisresume")
    public String hisResume(HttpServletRequest request, Model model) {
        try {
            String code = request.getParameter("code").trim();
            List<Object[]> lists = doGXService.getResumes(code);
            StringBuffer str = new StringBuffer();
            int num = 1;
            for (Object[] dr : lists) {
                str.append("<tr><td>" + num + "</td>");
                str.append("<td>" + dr[1] + "</td>");
                str.append("<td>" + dr[2] + "</td>");
                str.append("<td>" + dr[3] + "</td></tr>");
                num++;
            }
            model.addAttribute("res", str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/GXCampus/Resume/hisresume";
    }

    //[end]






    //[start] 未通过简历筛选

    @RequestMapping("/bz")
    public String BZ(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String id = request.getParameter("id").trim();
            model.addAttribute("id", id);
            model.addAttribute("pid", request.getParameter("pid").trim());
            model.addAttribute("fid", request.getParameter("fid").trim());
            model.addAttribute("deptcode", request.getParameter("deptcode").trim());
            DUserResume resume = doGXService.getDUserResume(id);
            model.addAttribute("bz", resume.getSxbz());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/GXCampus/Resume/bz";
    }


    //[end]


    //[start] 提交体检结果

    @RequestMapping(value = "/RAction", method = RequestMethod.POST)
    public void RAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择人员！", "no", response);
            } else {
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                String qystate = request.getParameter("qystate").trim();//体检结果
                String qyremark = request.getParameter("qyremark").trim();//体检备注

                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    if (utilService.FlowIsDoing(fid)) {
                        List<HRZZUser> editList = new ArrayList<HRZZUser>();
                        for (String uid : uids) {
                            HRZZUser usr = recommendService.getViewUser(uid);
                            if (usr.getDeptcode().equals(cuser.getUdept())
                                    && usr.getFqstate().equals("未放弃")
                                    && usr.getFid().equals(fid)
                            ) {
                                usr.setQystate(qystate);
                                usr.setQyremark(qyremark);
                                usr.setQydate(new Date());
                                usr.setQyuid(cuser.getId());
                                usr.setQyuname(cuser.getUname());

                                editList.add(usr);
                            }
                        }

                        if (editList.size() > 0) {
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中信息不支持此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        List editlist = new ArrayList();
                        List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                        ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                        for (HRZZUser user : users) {
                            if (user.getFid().equals(fid)&& user.getFqstate().equals("未放弃")) {
                                if(user.getQystate().equalsIgnoreCase("已签约")||user.getQystate().equalsIgnoreCase("无需签约")||user.getQystate().equalsIgnoreCase("合格")||user.getQystate().equalsIgnoreCase("已合格")) {
                                    user.setFid(nFlow.getId());
                                    user.setPath(user.getPath() + nFlow.getId() + "/");
                                    editlist.add(user);
                                }
                            }
                        }

                        if (editlist.size() > 0) {
                            nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                            editlist.add(nFlow);

                            utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
